package com.xinyiweidai.xinyiweidai;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.google.gson.Gson;
import com.lan.mylibrary.okhttp.L;
import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.StringCallback;
import com.lan.mylibrary.ui.MyToast;
import com.xinyiweidai.xinyiweidai.base.BaseActivity;
import com.xinyiweidai.xinyiweidai.bean.AppVersionBean;
import com.xinyiweidai.xinyiweidai.dialog.DownloadDialog;
import com.xinyiweidai.xinyiweidai.dialog.UpdateDialog;
import com.xinyiweidai.xinyiweidai.module.home.HomeFragment;
import com.xinyiweidai.xinyiweidai.module.message.MessageFragment;
import com.xinyiweidai.xinyiweidai.module.my.MyFragment;
import com.xinyiweidai.xinyiweidai.util.Api;
import com.xinyiweidai.xinyiweidai.util.SpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Request;


public class MainActivity extends BaseActivity implements UpdateDialog.OnUpdateDialogClickListener {


    private int oldPosition = 0;
    private long exitTime = 0;
    private Fragment[] fragmentArray;
    private String url, size;
    private int enforce;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        initFragment();
        initBottomView();
        initLoginStatus();
        getVersion();
    }


    private void initLoginStatus() {
        Constants.isLogin = SpUtil.getInstance().getLoginState();
    }


    private void initFragment() {
        fragmentArray = new Fragment[]{ HomeFragment.newInstance(),
                                        MessageFragment.newInstance(),
                                        MyFragment.newInstance()};
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frame_content, fragmentArray[0])
                .show(fragmentArray[0])
                .commit();
    }


    private void initBottomView() {
        BottomNavigationView bottomView = findViewById(R.id.bottomView);
        bottomView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.tab_home:
                    changeFragment(0);
                    return true;
                case R.id.tab_message:
                    changeFragment(1);
                    return true;
                case R.id.tab_my:
                    changeFragment(2);
                    return true;
            }
            return false;
        });
    }


    private void changeFragment(int newPosition) {
        if (newPosition == oldPosition) {
            return;
        }
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (!fragmentArray[newPosition].isAdded()) {
            ft.add(R.id.frame_content, fragmentArray[newPosition]);
        }
        ft.hide(fragmentArray[oldPosition]);
        ft.show(fragmentArray[newPosition]);
        ft.commit();

        oldPosition = newPosition;
    }


    private void getVersion() {
        Map<String, String> map = new HashMap<>();
        map.put("version", "android");
        OkHttpUtils
                .get()
                .url(Api.updateVersion)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                    }

                    @Override
                    public void onResponse(String response) {
                        L.e(response);
                        parseData(response);
                    }
                });
    }


    private void parseData(String response) {
        AppVersionBean bean = new Gson().fromJson(response, AppVersionBean.class);
        if (bean.getCode() == 1) {
            String newVersion = bean.getNewversion();
            if (newVersion.equals(BuildConfig.VERSION_NAME)) {
//                MyToast.showSuccess(this, "当前已是最新版本");
                return;
            }
            size = bean.getPackagesize();
            url = bean.getDownloadurl();
            enforce = bean.getEnforce();
            showUpdateDialog(size);
        }
    }


    private void showUpdateDialog(String size) {
        UpdateDialog fragment = UpdateDialog.newInstance(size, enforce, this);
//       fragment.setCancelable(false);//TODO 是否强制更新
        fragment.show(getSupportFragmentManager(), "update_dialog");
    }


    @Override
    public void onUpdateDialogClick() {
        DownloadDialog downloadDialogFragment = DownloadDialog.newInstance(size, url);
        downloadDialogFragment.setCancelable(false);
        downloadDialogFragment.show(getFragmentManager(), "download_dialog");
    }


    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            MyToast.showError(this, "双击退出");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }


    //解决App重启后导致Fragment重叠的问题
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);//TODO 为了不重叠，设置不保存
    }


}
